<template>
  <el-dialog
    append-to-body
    title='更换主题'
    :visible.sync='dialogShow'
    width='60%'
    :before-close='beforeClose'
    :close-on-click-modal='false'
    :close-on-press-escape='false'
    :destroy-on-close='true'
    custom-class='my-dialog'
    center
  >
    <div class='theme-box'>
      <div class='theme-box-title'>请选择主题进行更换</div>
      <div class='flex flex-space-around'>
        <div class='theme-box-item' v-for='(item, i) in presetsColor' :key='i'>
          <img
            class='theme-box-item-select'
            v-if='presetsIndex === i'
            src='@/assets/img/t-select.png'
            alt=''
          />
          <img
            class='theme-box-item-img'
            @click='choseColor(item, i)'
            :src="require('@/assets/img/' + item.img)"
          />
          <div class='theme-box-item-txt' :class="'txt' + i">
            {{ item.name }}
          </div>
          <div class='theme-box-item-tip' v-if='realIndex === i'>当前设置</div>
        </div>
      </div>
    </div>
    <span slot='footer' class='dialog-footer'>
      <el-button class='dialog-btn' type='primary' @click='changeTheme(theme)'
      >确 定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>

import axios from 'axios'

const version = require('element-ui/package.json').version // element-ui version from node_modules
// default color！！！！！！ 不能变
const ORIGINAL_THEME = '#409EFF'
export default {
  props: {
    dialogShow: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // isAll  0-不选 1-全选 2-半选
      presetsColor: [
        {
          name: '科技蓝',
          theme: 'basic0',
          color: '#1065BF',
          isAll: 0,
          img: 't-blue.png'
        },
        {
          name: '数码绿',
          theme: 'basic1',
          color: '#0B9678',
          isAll: 0,
          img: 't-green.png'
        }
      ],
      presetsIndex: 0,
      realIndex: 0,
      presetsTheme: '',
      chalk: '', // content of theme-chalk css
      theme: ''
    }
  },
  watch: {
    dialogShow(val) {
      if (val) {
        let theme = this.$store.state.settings.theme
        // 循环判断当前主题色是哪个
        this.presetsColor.forEach((item, index) => {
          // 主题色相同
          if (item.color === theme) {
            this.presetsIndex = index
            this.realIndex = index
          }
        })
      }
    }
  },
  created() {
    // 获取当前的主题色
    let theme = this.$store.state.settings.theme
    // 循环判断当前主题色是哪个
    this.presetsColor.forEach((item, index) => {
      // 主题色相同
      if (item.color === theme) {
        this.presetsIndex = index
        this.realIndex = index
      }
    })
    this.theme = theme
    // 初始化主题颜色
    this.changeTheme(this.$store.state.settings.theme)
    this.presetsTheme = this.$store.state.settings.bodyTheme
    this.changeBodyTheme(this.$store.state.settings.bodyTheme)
  },
  mounted() {
  },
  methods: {
    //换主题
    changeBodyTheme(theme) {
      // 存储bodyTheme
      this.$store.dispatch('settings/changeSetting', {
        key: 'bodyTheme',
        value: theme
      })
      // 修改为新的主题色
      window.document.documentElement.setAttribute('data-theme', theme)
    },
    // 选择主题颜色，点击就是全选
    choseColor(item, index) {
      this.presetsIndex = index
      this.presetsTheme = item.theme
      this.theme = item.color
    },
    beforeClose() {
      this.$emit('dialogClose', false)
    },
    async changeTheme(val) {
      const oldVal = this.chalk ? this.theme : ORIGINAL_THEME
      if (typeof val !== 'string') return
      const themeCluster = this.getThemeCluster(val.replace('#', ''))
      const originalCluster = this.getThemeCluster(oldVal.replace('#', ''))
      // const $message = this.$message({
      //   message: '  切换主题中....',
      //   customClass: 'theme-message',
      //   type: 'success',
      //   duration: 0,
      //   iconClass: 'el-icon-loading'
      // })
      const getHandler = (variable, id) => {
        return () => {
          const originalCluster = this.getThemeCluster(
            ORIGINAL_THEME.replace('#', '')
          )
          const newStyle = this.updateStyle(
            this[variable],
            originalCluster,
            themeCluster
          )
          let styleTag = document.getElementById(id)
          if (!styleTag) {
            styleTag = document.createElement('style')
            styleTag.setAttribute('id', id)
            document.head.appendChild(styleTag)
          }
          styleTag.innerText = newStyle
        }
      }
      if (!this.chalk) {
        const url = `${process.env.BASE_URL}element-theme/index.css`
        await this.getCSSString(url, 'chalk')
      }
      const chalkHandler = getHandler('chalk', 'chalk-style')
      chalkHandler()
      const styles = [].slice
        .call(document.querySelectorAll('style'))
        .filter((style) => {
          const text = style.innerText
          return (
            new RegExp(oldVal, 'i').test(text) && !/Chalk Variables/.test(text)
          )
        })
      styles.forEach((style) => {
        const { innerText } = style
        if (typeof innerText !== 'string') return
        style.innerText = this.updateStyle(
          innerText,
          originalCluster,
          themeCluster
        )
      })
      this.$emit('change', val)
      // $message.close()
      this.changeBodyTheme(this.presetsTheme)
      this.$emit('dialogClose', false)
    },
    //---------------------------------------------------------
    updateStyle(style, oldCluster, newCluster) {
      let newStyle = style
      oldCluster.forEach((color, index) => {
        newStyle = newStyle.replace(new RegExp(color, 'ig'), newCluster[index])
      })
      return newStyle
    },
    get111() {
      axios.get('/index.css')
        .then(response => {
          // 处理响应的内容
          console.log(response.data)
        }).catch(error => {
        // 处理错误
        console.error('Error fetching CSS file:', error)
      })
    },
    getCSSString(url, variable) {
      return  axios.get('/index.css')
        .then(response => {
          // 处理响应的内容
          this[variable] = response.data.replace(/@font-face{[^}]+}/, '')
        }).catch(error => {
        // 处理错误
        console.error('Error fetching CSS file:', error)
      })
      //    this.$axios
      //     .create({
      //       baseURL: "",
      //       timeout: 5000,
      //       headers: { "Content-type": "multipart/form-data" }
      //     })
      //     .get("/index.css")
      //     .then(res => {
      //       console.log(res);
      //     });
      //
      // }
      // return new Promise((resolve) => {
      //   const xhr = new XMLHttpRequest()
      //   xhr.onreadystatechange = () => {
      //     if (xhr.readyState === 4 && xhr.status === 200) {
      //       this[variable] = xhr.responseText.replace(/@font-face{[^}]+}/, '')
      //       resolve()
      //     }
      //   }
      //   xhr.open('GET', 'index.css')
      //   xhr.send()
      // })
    },
    getThemeCluster(theme) {
      const tintColor = (color, tint) => {
        let red = parseInt(color.slice(0, 2), 16)
        let green = parseInt(color.slice(2, 4), 16)
        let blue = parseInt(color.slice(4, 6), 16)
        if (tint === 0) {
          // when primary color is in its rgb space
          return [red, green, blue].join(',')
        } else {
          red += Math.round(tint * (255 - red))
          green += Math.round(tint * (255 - green))
          blue += Math.round(tint * (255 - blue))
          red = red.toString(16)
          green = green.toString(16)
          blue = blue.toString(16)
          return `#${red}${green}${blue}`
        }
      }
      const shadeColor = (color, shade) => {
        let red = parseInt(color.slice(0, 2), 16)
        let green = parseInt(color.slice(2, 4), 16)
        let blue = parseInt(color.slice(4, 6), 16)
        red = Math.round((1 - shade) * red)
        green = Math.round((1 - shade) * green)
        blue = Math.round((1 - shade) * blue)
        red = red.toString(16)
        green = green.toString(16)
        blue = blue.toString(16)
        return `#${red}${green}${blue}`
      }
      const clusters = [theme]
      for (let i = 0; i <= 9; i++) {
        clusters.push(tintColor(theme, Number((i / 10).toFixed(2))))
      }
      clusters.push(shadeColor(theme, 0.1))
      return clusters
    }
  }
}
</script>

<style lang='scss' scoped>
.theme-box {
  color: #ffffff;
  text-align: center;

  &-title {
    font-size: 20px;
    margin-bottom: 30px;
  }

  &-item {
    margin-bottom: 20px;
    position: relative;

    &-select {
      position: absolute;
      top: 35%;
      left: 50%;
      transform: translate(-50%, -35%);
      width: 40%;
    }

    &-img {
      width: 90%;
      margin-bottom: 20px;
      cursor: pointer;
    }

    &-txt {
      font-size: 20px;
      font-weight: 600;
      color: #3f9afd;
      background: url('~@/assets/img/t-b-txt.png') no-repeat center;
      background-size: 100% 100%;
      height: 40px;
      line-height: 40px;
      margin-bottom: 20px;
    }

    &-tip {
      font-size: 16px;
      font-weight: 400;
      color: #ffffff;
    }

    .txt1 {
      color: #0ca47e;
    }
  }
}
</style>
